//公共函数
export function boolToYN(value: boolean | string): string {
  return value ? "Y" : "N";
}

//对应映射
export const vehTypeMap: { [key: string]: vehType } = {
  "Large Good Vehicle": "LGV",
  "Motor Cycle": "MOTOR_CYCLE",
  "Private Car": "PRIVATE_CAR",
};
//对象里面 属性值转化为 Y N
export function convertBooleansToYN(
  obj: Record<string, boolean | string>
): Record<string, string> {
  const result: Record<string, string> = {};

  Object.entries(obj).forEach(([key, value]) => {
    result[key] = boolToYN(value as boolean); // 确保传入的是 boolean 类型
  });

  return result;
}

//转为二进制文件
export function convertFileToBase64(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();

    reader.onload = () => {
      // 将结果作为 Base64 字符串返回
      resolve(reader.result as string); // 使用类型断言
    };

    reader.onerror = (error) => {
      reject(error);
    };

    // 读取文件并将其编码为 Data URL（Base64）
    reader.readAsDataURL(file);
  });
}
// 将 Base64 字符串转换为 Blob
const base64ToBlob = (base64: string, type: string) => {
  const byteCharacters = atob(base64);
  const byteNumbers = new Array(byteCharacters.length);
  for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
  }
  const byteArray = new Uint8Array(byteNumbers);
  return new Blob([byteArray], { type });
};

export const createFileFromBase64 = (
  base64: string,
  fileName: string,
  type: string
) => {
  const blob = base64ToBlob(base64, type);
  return new File([blob], fileName, { type });
};
